package org.jeecg.modules.mes.order.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.order.entity.ExpApplyBill;
import org.jeecg.modules.mes.order.entity.ExpApplyMain;
import org.jeecg.modules.mes.order.service.IExpApplyBillService;
import org.jeecg.modules.mes.order.service.IExpApplyMainService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 出口申请单主表
 * @Author: jeecg-boot
 * @Date:   2021-04-07
 * @Version: V1.0
 */
@Api(tags="出口申请单主表")
@RestController
@RequestMapping("/order/expApplyMain")
@Slf4j
public class ExpApplyMainController extends JeecgController<ExpApplyMain, IExpApplyMainService> {

	@Autowired
	private IExpApplyMainService expApplyMainService;

	@Autowired
	private IExpApplyBillService expApplyBillService;


	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param expApplyMain
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "出口申请单主表-分页列表查询")
	@ApiOperation(value="出口申请单主表-分页列表查询", notes="出口申请单主表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ExpApplyMain expApplyMain,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ExpApplyMain> queryWrapper = QueryGenerator.initQueryWrapper(expApplyMain, req.getParameterMap());
		Page<ExpApplyMain> page = new Page<ExpApplyMain>(pageNo, pageSize);
		IPage<ExpApplyMain> pageList = expApplyMainService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
     *   添加
     * @param expApplyMain
     * @return
     */
    @AutoLog(value = "出口申请单主表-添加")
    @ApiOperation(value="出口申请单主表-添加", notes="出口申请单主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ExpApplyMain expApplyMain) {
        expApplyMainService.save(expApplyMain);
        return Result.ok("添加成功！");
    }

    /**
     *  编辑
     * @param expApplyMain
     * @return
     */
    @AutoLog(value = "出口申请单主表-编辑")
    @ApiOperation(value="出口申请单主表-编辑", notes="出口申请单主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ExpApplyMain expApplyMain) {
        expApplyMainService.updateById(expApplyMain);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "出口申请单主表-通过id删除")
    @ApiOperation(value="出口申请单主表-通过id删除", notes="出口申请单主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        expApplyMainService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "出口申请单主表-批量删除")
    @ApiOperation(value="出口申请单主表-批量删除", notes="出口申请单主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.expApplyMainService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExpApplyMain expApplyMain) {
        return super.exportXls(request, expApplyMain, ExpApplyMain.class, "出口申请单主表");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ExpApplyMain.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/
	

    /*--------------------------------子表处理-出口申请单-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "出口申请单-通过主表ID查询")
	@ApiOperation(value="出口申请单-通过主表ID查询", notes="出口申请单-通过主表ID查询")
	@GetMapping(value = "/listExpApplyBillByMainId")
    public Result<?> listExpApplyBillByMainId(ExpApplyBill expApplyBill,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<ExpApplyBill> queryWrapper = QueryGenerator.initQueryWrapper(expApplyBill, req.getParameterMap());
        Page<ExpApplyBill> page = new Page<ExpApplyBill>(pageNo, pageSize);
        IPage<ExpApplyBill> pageList = expApplyBillService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

	/**
	 * 添加
	 * @param expApplyBill
	 * @return
	 */
	@AutoLog(value = "出口申请单-添加")
	@ApiOperation(value="出口申请单-添加", notes="出口申请单-添加")
	@PostMapping(value = "/addExpApplyBill")
	public Result<?> addExpApplyBill(@RequestBody ExpApplyBill expApplyBill) {
		ExpApplyMain main=expApplyMainService.getById(expApplyBill.getExpMainId());
		expApplyBill.setOutBillNo(main.getOrderCode());
		expApplyBill.setCurr(main.getCurrency());
		expApplyBill.setCompanyCode("500666002U");
		expApplyBill.setCompanyMergerKey("");
		expApplyBill.setGwId(IdUtil.simpleUUID());
		expApplyBill.setOptLock(0);
		expApplyBill.setExpApplyState("未上传");
		expApplyBillService.save(expApplyBill);
		return Result.ok("添加成功！");
	}

    /**
	 * 编辑
	 * @param expApplyBill
	 * @return
	 */
	@AutoLog(value = "出口申请单-编辑")
	@ApiOperation(value="出口申请单-编辑", notes="出口申请单-编辑")
	@PutMapping(value = "/editExpApplyBill")
	public Result<?> editExpApplyBill(@RequestBody ExpApplyBill expApplyBill) {
		expApplyBillService.updateById(expApplyBill);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出口申请单-通过id删除")
	@ApiOperation(value="出口申请单-通过id删除", notes="出口申请单-通过id删除")
	@DeleteMapping(value = "/deleteExpApplyBill")
	public Result<?> deleteExpApplyBill(@RequestParam(name="id",required=true) String id) {
		expApplyBillService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出口申请单-批量删除")
	@ApiOperation(value="出口申请单-批量删除", notes="出口申请单-批量删除")
	@DeleteMapping(value = "/deleteBatchExpApplyBill")
	public Result<?> deleteBatchExpApplyBill(@RequestParam(name="ids",required=true) String ids) {
	    this.expApplyBillService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportExpApplyBill")
    public ModelAndView exportExpApplyBill(HttpServletRequest request, ExpApplyBill expApplyBill) {
		 // Step.1 组装查询条件
		 QueryWrapper<ExpApplyBill> queryWrapper = QueryGenerator.initQueryWrapper(expApplyBill, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<ExpApplyBill> pageList = expApplyBillService.list(queryWrapper);
		 List<ExpApplyBill> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "出口申请单"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, ExpApplyBill.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出口申请单报表", "导出人:" + sysUser.getRealname(), "出口申请单"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExpApplyBill/{mainId}")
    public Result<?> importExpApplyBill(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<ExpApplyBill> list = ExcelImportUtil.importExcel(file.getInputStream(), ExpApplyBill.class, params);
				 for (ExpApplyBill temp : list) {
                    temp.setExpMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 expApplyBillService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-出口申请单-end----------------------------------------------*/

	 /*--------------------------------上传关务-进口申请单子表-begin----------------------------------------------*/

	 @AutoLog(value = "出口申请单-上传关务")
	 @ApiOperation(value="出口申请单-上传关务", notes="根据出口申请单主表id获取子表信息，调用上传关务系统")
	 @GetMapping(value = "/insertSqlServer")
	 public Result<?> importPurchaseSqlServer(@RequestParam(name="id",required=true) String id) {
		 ExpApplyMain expmain = expApplyMainService.getById(id);
		 if(expmain!=null){
			 if("已上传".equals(expmain.getState())){
				 return Result.error("该出口申请单已上传关务，请重新创建新的申请单！");
			 }
			 //上传关务系统
			 expApplyMainService.insertSqlServer(expmain);
		 }else {
			 Result.error("未找到该出口申请单");
		 }
		 return Result.OK("上传完成");
	 }

	 /*--------------------------------上传关务-进口申请单子表-end----------------------------------------------*/


}
